package com.easyidea.its.util;

import java.io.InputStream;

import org.apache.log4j.Logger;

import com.enterprisedt.net.ftp.FTPTransferType;

public class FTPClientUtil {
	private static final Logger log = Logger.getLogger(FTPClientUtil.class);

	

	public static InputStream downLoadFtpFile(FTPConfig config) throws Exception {
		String host = config.getHost();
		String username = config.getUserName();
		String password = config.getPassword();
		String remotePaths = config.getRemotePaths();
		int index = remotePaths.lastIndexOf(config.getFileSeperator());
		String file_ab_path = remotePaths.substring(0, index);
		String fileName = remotePaths.substring((index + 1), remotePaths.length());
		EncodingFileTransferClient client = new EncodingFileTransferClient();
		try {
		client.setRemoteHost(host);
		client.setRemotePort(21);
		client.setUserName(username);
		client.setPassword(password);
		long startTime = System.currentTimeMillis();

		try {

			client.setControlEncoding("GBK");
			client.setTimeout(1200);
			client.connect();

			client.setContentType(FTPTransferType.BINARY);
			client.changeDirectory(file_ab_path);
		} catch (Exception e) {
			client.disconnect();
			client.setControlEncoding("utf-8");
			client.setTimeout(1200);
			client.connect();
			client.setContentType(FTPTransferType.BINARY);
			client.changeDirectory(file_ab_path);
		}
		long endTime = System.currentTimeMillis();
		log.error("Connect ftp server spend time ..........." + (endTime - startTime));
		client.getAdvancedSettings().setTransferBufferSize(2048);
		InputStream is = client.downloadStream(fileName);		
		return is;
		} catch(Exception e){
			throw new Exception(e.getMessage());
		}
	}

	public static FTPConfig buildFtpConfig(String firstPicPath, Integer left, Integer top, Integer height, Integer width) {
		//String firstPicPath = tracklog.getFirstPicPath();
		String[] str = firstPicPath.split("@");
		String user_pass = str[0].substring(6);

		String userName = user_pass.split(":")[0];
		String password = user_pass.split(":")[1];
		// System.out.println(userName + "---" + password);
		String host_remotePaths = str[1];
		int index = host_remotePaths.indexOf("/");
		String host = host_remotePaths.substring(0, index);
		String remotePaths = "";
		String[] tmp = host_remotePaths.substring(index, host_remotePaths.length()).split("/");
		for (int i = 0; i < tmp.length; i++) {
			remotePaths += "/" + tmp[i];
		}
		FTPConfig config = new FTPConfig();
		config.setHost(host);
		config.setUserName(userName);
		config.setPassword(password);
		config.setRemotePaths(remotePaths.substring(1));
		config.setTopLeftX(left == null ? 0: left);
		config.setTopLeftY(top == null ? 0: top);
		config.setDestHeight(height == null ? 0: height);
		config.setDestWidth(width == null ? 0: width);
		return config;
	}
}
